﻿using BrnMall.Core;
using BrnMall.Manager.Domain.User;
using BrnMall.Manager.Manager.User;
using BrnMall.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Business
{
    public static class DirectPaymentService
    {
        private static string _osnformat;//订单编号格式
        static DirectPaymentService()
        {
            _osnformat = BMAConfig.MallConfig.OSNFormat;
        }
        /// <summary>
        /// 生成订单编号
        /// </summary>
        /// <param name="storeId">店铺id</param>
        /// <param name="uid">用户id</param>
        /// <param name="shipRegionId">配送区域id</param>
        /// <param name="addTime">下单时间</param>
        /// <returns>订单编号</returns>
        public static string GeneratePSN(int storeId, int uid, DateTime addTime)
        {
            StringBuilder osn = new StringBuilder(_osnformat);
            osn.Replace("{storeid}", storeId.ToString());
            osn.Replace("{uid}", uid.ToString());
            osn.Replace("{srid}", "0");
            osn.Replace("{addtime}", addTime.ToString("yyyyMMddHHmmss"));
            return osn.ToString();
        }
        /// <summary>
        /// 获得订单信息
        /// </summary>
        /// <param name="oid">订单id</param>
        /// <returns>订单信息</returns>
        public static DirectPayment GetPaymentByPid(int pid)
        {
            if (pid > 0)
                return DirectPaymentManager.GetPaymentByPid(pid);
            else
                return null;
        }
        /// <summary>
        /// 获得订单信息
        /// </summary>
        /// <param name="psn">订单编号</param>
        /// <returns>订单信息</returns>
        public static DirectPayment GetPaymentByPSN(string psn)
        {
            if (!string.IsNullOrWhiteSpace(psn))
                return DirectPaymentManager.GetPaymentByPSN(psn);
            return null;
        }
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="uid">用户信息</param>
        /// <param name="storeid">店铺信息</param>
        /// <param name="payCreditCount">支付积分数</param>
        /// <param name="couponList">优惠劵列表</param>
        /// <returns>订单信息</returns>
        public static DirectPayment CreateDirectPayment(int uid, int storeid, decimal orderAmount, decimal payCash, int payCreditCount, List<CouponInfo> couponList, string ip)
        {
            DateTime nowTime = DateTime.Now;

            DirectPayment payment = new DirectPayment();

            payment.PSN = GeneratePSN(storeid, uid, nowTime);
            payment.Uid = uid;
            payment.OrderAmount = orderAmount;
            //验证 余额支付
            if (payCash > 0)
            {
                var userCash = Manager.Manager.User.UserCashManager.GetInfo(uid);
                decimal balance = CashOrders.DecodeCash(userCash.Cash);
                if (userCash == null || payCash > balance)
                    throw new Exception(string.Format("余额支付不能超过{0}元", balance));
                payment.PayCash = payCash;
            }


            decimal payCreditMoney = Credits.PayCreditsToMoney(storeid, payCreditCount);

            if (payment.OrderAmount >= payCreditMoney)
            {
                payment.PayCreditCount = payCreditCount;
                payment.PayCreditMoney = payCreditMoney;
                payCreditCount = 0;
            }
            else
            {
                int orderPayCredits = Credits.MoneyToPayCredits(storeid, payment.OrderAmount);
                payment.PayCreditCount = orderPayCredits;
                payment.PayCreditMoney = payment.OrderAmount;
                payCreditCount = payCreditCount - orderPayCredits;
            }

            payment.CouponMoney = Coupons.SumCouponMoney(couponList);
            payment.CouponIds = string.Join(",", couponList.Select(t => t.CouponId).ToList());
            payment.SurplusMoney = payment.OrderAmount - payment.PayCreditMoney - payment.CouponMoney - payCash;
            if (payment.SurplusMoney < 0)
                payment.SurplusMoney = 0;
            payment.OrderState = (payment.SurplusMoney <= 0) ? 1 : 0;
            payment.AddTime = nowTime;
            payment.StoreId = storeid;
            payment.PaySystemName = "wechat";
            try
            {
                //添加订单
                int oid = DirectPaymentManager.AddDirectPayment(payment);
                if (oid > 0 )
                {
                    payment.Pid = oid;


                    //使用支付积分
                    Credits.PayDirectPayment(uid, payment.Pid, payment.PSN, payment.PayCreditCount, nowTime);
                    //使用优惠劵
                    foreach (CouponInfo couponInfo in couponList)
                    {
                        if (couponInfo.Uid > 0)
                            Coupons.UseCoupon(couponInfo.CouponId, oid, nowTime, ip);
                        else
                            Coupons.ActivateAndUseCoupon(couponInfo.CouponId, uid, oid, nowTime, ip);
                    }
                    //使用账户余额
                    if (payCash > 0&& payment.OrderState == 1)
                    {
                        CashOrders.ConsumeCash(uid, storeid, payCash, "当面付使用余额支付");
                    }
                    return payment;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return null;
        }

    }
}
